import React, {Component} from 'react';
import './index.less';
import {connect} from 'src/hrpub/common/store';
import {isBlackBg} from 'src/hrpub/common/utils/utils';
// 引入 ECharts 主模块
import echarts from 'echarts/lib/echarts';
// 引入柱状图
import 'echarts/lib/chart/bar';
// 引入饼形图
import 'echarts/lib/chart/pie';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
// 引入图例
// import 'echarts/lib/component/legend';
import 'echarts/lib/component/legendScroll';
import {COMMON} from "../../../../unit/util";

class Echarts extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }

    componentWillReceiveProps(nextProps, nextContext) {
        if (nextProps.pk_org !== this.props.pk_org || nextProps.pk_psncl !== this.props.pk_psncl) {
            this.getChartData(nextProps);
        }
    }

    componentDidMount() {
        setTimeout(this.drawChart, 100)
    }

    drawChart = () => {
        // 基于准备好的dom，初始化echarts实例
        this.ageChart = echarts.init(document.getElementById('age-left'));
        this.eduChart = echarts.init(document.getElementById('edu-right'));
        //  请求数据后 在初始化chart
        this.getChartData(this.props);
    };

    /**
     * 获取图表数据
     * @returns {Promise<void>}
     */
    getChartData = async (props) => {
        let postData = {
            pk_org: props.pk_org,
            pk_psncl: props.pk_psncl
        };
        let res = await props.dispatch({
            type: 'staffCom/queryAgeEduEchart',
            payload: {
                postData
            }
        });
        if (!res.success) return;
        this.formatData(res);
    };

    /**
     * 处理返回数据
     * @param res
     */
    formatData = (res) => {
        if (!res.data) return;
        let leftXData = [], leftYData = [], leftShadows = [], rightData = [];
        let language = this.props.staffCom.language;
        // let ageArr = ['i0_25', 'i26_30', 'i31_45', 'i46_55', 'i55_'];
        let ageArr = (res.data.age && Object.keys(res.data.age)) || [];
        let maxValue = 0;
        ageArr.forEach(function (key) {
            let count = res.data.age[key];
            leftYData.push(count);
            maxValue = (count-0) <= maxValue ? maxValue : (count-0);
            let leftValArr = key.split('i')[1].split('_');
            if (leftValArr[0] === "0") {
                // 第一个
                leftXData.push(language['gx6008-000175']);
                return
            }
            if (!leftValArr[1]) {
                // 最后一个
                leftXData.push(language['gx6008-000179']);
                return
            }
            leftXData.push(leftValArr.join('-'));
        });
        if (maxValue == 0) {
            maxValue = 1;
        }
        for (let i = 0; i < ageArr.length; i++) {
            leftShadows.push(maxValue);
        }

        res.data.edu.forEach(function (item) {
            if (item.cnt) {
                rightData.push({
                    name: item.name,
                    value: item.cnt
                });
            }
        });
        let options = this.comboOption(leftXData, leftYData, leftShadows, rightData);
        // 绘制图表
        this.ageChart.setOption(options[0]);
        this.eduChart.setOption(options[1]);
    }

    /**
     *
     * @param leftXData ['0-25', '26-30', '31-45', '46-55', '56以上']
     * @param leftYData [480, 385, 342, 480, 205]
     * @param leftShadows [500, 500, 500, 500, 500]
     * @param rightData [
     { value: 1, name: '晋升' },
     { value: 2, name: '组织变更' },
     { value: 3, name: '工作地变更' },
     { value: 4, name: '岗位变更' }
     ]
     * @returns {*[]}
     */
    comboOption = (leftXData, leftYData, leftShadows, rightData) => {
        // let leftXData = [this.props.staffCom.language['gx6008-000175'], '26-30', '31-45', '46-55', this.props.staffCom.language['gx6008-000179']];
        let lineColor = isBlackBg() ? "#39393f" : "#ccc";
        let optionLeft = {
            title: {
                text: null
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: `${this.props.staffCom.language['gx6008-000136']}: {b}<br />${this.props.staffCom.language['gx6008-000137']}: {c}`
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                // data: ['0-25', '26-30', '31-45', '46-55', '56以上'],
                data: leftXData,
                splitLine: { //隐藏网格线
                    show: false
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: lineColor
                    }
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    interval: 0,
                    textStyle: {
                        color: '#999',
                        fontSize: leftXData.length > 5 ? 8 : 12
                    }
                }
            },
            yAxis: {
                type: 'value',
                splitLine: {
                    show: false
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: lineColor
                    }
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    textStyle: {
                        color: '#999'
                    }
                }
            },
            series: [{
                name: this.props.staffCom.language['gx6008-000138'],
                type: 'bar',
                //data: [480, 385, 342, 480, 205], // @1: data
                data: leftYData,
                barMaxWidth: 25,
                itemStyle: {
                    normal: {
                        color: '#44bde4',
                        label: {
                            show: true,
                            position: 'top',
                            textStyle: {
                                color: '#666'
                            }
                        }
                    }
                }
            }, { // For shadow
                type: 'bar',
                itemStyle: {
                    normal: {color: 'rgba(0,0,0,0.05)'}
                },
                barGap: '-100%',
                barCategoryGap: '40%',
                barMaxWidth: 25,
                //data: [500, 500, 500, 500, 500],
                data: leftShadows,
                animation: false
            }]
        };

        let hideZeroFlag = false;
        if (rightData) {
            for (let i = 0; i < rightData.length; i++) {
                let data = rightData[i];
                if (data['value']) {
                    let dataVal = data['value'] - 0;
                    if (dataVal !== 0) {
                        hideZeroFlag = true;
                        break
                    }
                }
            }
        }
        let optionRight = {
            tooltip: {
                trigger: 'item',
                formatter: "{b}: {c} ({d}%)"
            },
            legend: {
                type: 'scroll',
                bottom: '10px',
                selectedMode: false,
                data: rightData,
                textStyle: {
                    color: "#999"
                }
            },
            color: ['#ff7f50', '#87cefa', '#da70d6', '#32cd32', '#6495ed', '#ff69b4', '#ba55d3', '#cd5c5c', '#ffa500', '#40e0d0', '#1e90ff', '#ff6347', '#7b68ee', '#00fa9a', '#ffd700', '#6699FF', '#ff6666', '#3cb371', '#b8860b', '#30e0e0'],
            series: [{
                name: this.props.staffCom.language['gx6008-000139'],
                type: 'pie',
                radius: ['40%', '60%'],
                center: ['50%', '45%'],
                avoidLabelOverlap: false,
                connectNulls: false,
                label: {
                    normal: {
                        show: true,
                        position: 'outside',
                        textStyle: {
                            fontSize: 12,
                        },
                        formatter: function (val) {
                            let valData = val.value - 0;

                            // 如果valData的值为0 且其他值不为0 则返回 “”   如果其他值都为0则返回0
                            if (valData === 0 && hideZeroFlag) {
                                return '';
                            }

                            return valData + ''
                        }//'{c}'
                    },
                    emphasis: {
                        show: true,
                        position: 'center top',
                        textStyle: {
                            fontSize: 16,
                            fontWeight: 'bold',
                        }
                    }
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                data: rightData
            }]
        };
        return [optionLeft, optionRight];
    };

    render() {
        const {staffCom} = this.props;
        return (
            <div className={'age-edu'}>
                <div className={`chart-title  ${this.props.titleClass}`}>
                    <div className={`title-name`}>
                        {staffCom.language["gx6008-000180"]}
                    </div>
                    <div className={'more'} onClick={() => {
                        this.props.showDetail(COMMON.pageAgeEdu)
                    }}>
                    </div>
                </div>
                <div className={"chart-content"}>
                    <div id="age-left">

                    </div>
                    <div id="edu-right">

                    </div>
                </div>
            </div>
        );
    }
}

export default Echarts;
